import React, { useContext, useEffect } from 'react';
import { View, Text } from '@tarojs/components';
import { FormContext } from './FormContext';
import { FormItemProps } from './types';

const FormItem: React.FC<FormItemProps> = (props) => {
  const { name, label, rules = [], children } = props;
  const { formData, errors, updateField, registerField, unregisterField } = useContext(FormContext);

  // 注册和注销表单项
  useEffect(() => {
    registerField(name);
    return () => {
      unregisterField(name);
    };
  }, [name, registerField, unregisterField]);

  // 克隆子元素并注入value和onChange
  const child = React.Children.only(children) as React.ReactElement;
  const enhancedChild = React.cloneElement(child, {
    value: formData[name],
    onChange: (value) => {
      updateField(name, value);
      if (child.props.onChange) {
        child.props.onChange(value);
      }
    },
  });

  return (
    <View className='form-item'>
      {label && <Text className='form-item-label'>{label}</Text>}
      <View className='form-item-control'>
        {enhancedChild}
        {errors[name] && <Text className='form-item-error'>{errors[name]}</Text>}
      </View>
    </View>
  );
};

export default FormItem;
